<template>
  <div>
    <van-form>
      <van-cell title="选择预约日期" :value="date" @click="show = true" />
      <van-calendar v-model="show" @confirm="onConfirm1" />
      <van-cell-group>
        <van-cell v-for="item in list" :key="item.id" :title="item.name">
          <template #right-icon>
            <van-button size="mini" type="primary" @click="save(item.id,item.name)">预约</van-button>
          </template>
        </van-cell>
      </van-cell-group>

    </van-form>
  </div>
</template>

<script>
import vaccine from '@/api/vaccine'
import vaccintor from '@/api/vaccinator'
import appointment from '@/api/appointment'
import Cookies from 'js-cookie'
import { Toast } from 'vant'

export default {
  name: 'Reservation',
  data() {
    return {
      date: '',
      vaccineAppointment: {
        adate: '',
        vaccinatorId: '',
        vaccinatorName: '',
        vaccineId: '',
        vaccineName: '',
        hospitalId: '',
        hospitalName: ''
      },
      list: [],
      show: false
    }
  },
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
      this.fetchDataBySysId(Cookies.get('Sysid'))
    }
  },
  methods: {
    formatDate(date) {
      const y = new Date()
      return `${y.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    onConfirm1(date) {
      this.show = false
      this.date = this.formatDate(date)
      this.vaccineAppointment.adate = this.date
    },
    save(id, name) {
      this.vaccineAppointment.vaccinatorId = id
      this.vaccineAppointment.vaccinatorName = name
      this.vaccineAppointment.sysUserId = Cookies.get('Sysid')
      if (this.vaccineAppointment.vaccinatorId === '' ||
        this.vaccineAppointment.vaccineId === '' ||
        this.vaccineAppointment.vaccineName === '' ||
        this.vaccineAppointment.sysUserId === '' ||
        this.vaccineAppointment.adate === '' ||
        this.vaccineAppointment.hospitalId === '' ||
        this.vaccineAppointment.hospitalName === ''
      ) {
        Toast.fail('有空项目不能提交')
      } else {
        appointment.save(this.vaccineAppointment).then(response => {
          this.$router.push({ path: '/' })
          Toast.success('预约成功')
        })
      }
    },
    fetchDataById(id) {
      vaccine.getById(id).then(response => {
        this.vaccineAppointment.hospitalId = response.data.item.hospitalId
        this.vaccineAppointment.hospitalName = response.data.item.hospitalName
        this.vaccineAppointment.vaccineId = response.data.item.vaccineId
        this.vaccineAppointment.vaccineName = response.data.item.vaccineName
      })
    },
    fetchDataBySysId(searchObj) {
      vaccintor.List(searchObj).then(response => {
        this.list = response.data.rows
      })
    }

  }
}
</script>

<style scoped>

</style>
